package com.pingao.mp.modular.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pingao.mp.modular.sys.entity.Log;
import com.pingao.mp.modular.sys.entity.User;
import com.pingao.mp.modular.sys.mapper.LogMapper;
import com.pingao.mp.modular.sys.mapper.UserMapper;
import com.pingao.mp.modular.sys.service.LogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class LogServiceImpl extends ServiceImpl<LogMapper, Log> implements LogService{
    @Autowired
    private UserMapper userMapper;

    @Override
    public IPage<Log> getList(Integer pageNumber, Integer pageSize, String searchText, String sortName, String sortOrder) {
        IPage<Log> p = new Page<>(pageNumber, pageSize);
        QueryWrapper<Log> wrapper = new QueryWrapper<Log>();
        if (searchText != null && searchText.length() > 0) {
            wrapper.and(q -> (
                    q.like(Log.COL_METHOD, searchText).or().like(Log.COL_SERVLET_PATH, searchText)
            ));
        }

        wrapper.orderByDesc(Log.COL_CREATE_TIME);
        baseMapper.selectPage(p, wrapper);
        addOtherFiled(p.getRecords());
        return p;
    }

    private void addOtherFiled(List<Log> records) {
        Set<Long> userIds = new HashSet<>();
        for (Log record : records) {
            if (record.getUserId() != null) {
                userIds.add(record.getUserId());
            }
        }
        List<User> users = new ArrayList<>();
        if (userIds.size() > 0) {
            users = userMapper.selectList(new QueryWrapper<User>().in(User.COL_ID, userIds).select(User.COL_ID, User.COL_NAME, User.COL_NICK));
        }

        for (Log record : records) {
            for (User user : users) {
                if (user.getId().equals(record.getUserId())) {
                    record.setUserName(user.getName() + "-" + user.getNick());
                    break;
                }
            }
        }
    }
}
